package com.chazz.servlet.cart;

import com.chazz.entity.GoodsInfo;
import com.chazz.dao.ShoppingcarDao;
import com.chazz.dao.Sku2Dao;
import com.chazz.dao.impl.CartDaoImpl;
import com.chazz.dao.impl.ShoppingcarDaoImpl;
import com.chazz.dao.impl.Sku2DaoImpl;
import com.chazz.entity.*;
import com.chazz.service.CartService;
import com.chazz.service.impl.CartServiceImpl;
import com.chazz.utils.JSONUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.*;

@WebServlet("/cart.do")
public class CartServlet extends HttpServlet {
    private Sku2Dao skuDaoImpl = new Sku2DaoImpl();
    private CartService cartServiceImpl = new CartServiceImpl();
    private CartServiceImpl cartService = new CartServiceImpl();
    private ShoppingcarDao shoppingcarDaoImpl = new ShoppingcarDaoImpl();
    private CartDaoImpl cartDao = new CartDaoImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        if(method==null){
            //判断是否登录
            login(req,resp);
        }else if("delete".equals(method)){
            //删除所选的商品
            delete(req,resp);
        }else if("add".equals(method)) {
            //添加
            add(req,resp);
        }else if("deleteOne".equals(method)){
            //删除所选的一个
            deleteOne(req,resp);
        }else if("deleteAll".equals(method)){
            //删除全部
            deleteAll(req,resp);
        }else if("list".equals(method)){
            list(req,resp);
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        String goods = req.getParameter("goods");
        System.out.println(goods);
        List<GoodsInfo> goodsInfos = JSONUtils.toList(GoodsInfo.class,goods);
        Double totalprice = 0.0;
        for(GoodsInfo goodsInfo : goodsInfos){
            String price = skuDaoImpl.findByGid(goodsInfo.getGoodsid()).getPrice();
            totalprice += goodsInfo.getCount()*Double.parseDouble(price);
        }
        DecimalFormat df = new DecimalFormat("#.00");
        String totalpriceStr = df.format(totalprice);
        PrintWriter out = resp.getWriter();
        out.write(totalpriceStr);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("add方法被调用");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        String gid =  req.getParameter("gid");

        if(user==null){
            cartService.cartAdd(Integer.parseInt(gid));
        }else{
            cartServiceImpl.CartGoodAdd(Integer.parseInt(gid),user.getId());
        }
        login(req,resp);
    }

    private void deleteAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if(user==null){
            cartService.deleteAll();
        }else{
            List<CartDetails> cartDetails = (List<CartDetails>) session.getAttribute("cartDetails");
            Integer sid = cartDetails.get(0).getCart().getSid();
            cartServiceImpl.deleteBySid(sid);
        }
        login(req,resp);
    }

    private void deleteOne(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //将cart中的count减一
        String cid = req.getParameter("cid");
        String gid = req.getParameter("gid");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if(user==null){
            cartService.deleteCount(Integer.parseInt(gid));
        }else{
            Cart cart = cartServiceImpl.findById(Integer.parseInt(cid));
            if(cart.getCount()-1<=0){
                cartServiceImpl.deleteByGid(Integer.parseInt(gid));
            }else{
                cartServiceImpl.updateCartCount((cart.getCount()-1),cart.getId());
            }
        }
        login(req,resp);
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String gid = req.getParameter("gid");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if(user==null){
            cartService.delete(Integer.parseInt(gid));
        }else{
            cartServiceImpl.deleteByGid(Integer.parseInt(gid));
        }
        login(req,resp);
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        Boolean flog = false;
        HttpSession session = req.getSession();
        session.setMaxInactiveInterval(60*60*60);

        User user = (User) session.getAttribute("user");
        if(user.getId()==0){;
            //跳转未登录的购物车页面
            List<CartDetails> cartDetails = cartService.findDetailsByGid();
            Cookie cookie = new Cookie("chen","chen");
            for(int i = 0;i<cartDetails.size();i++){
                cookie = new Cookie("gid"+i,cartDetails.get(i).getGood().getGoodsid().toString());
            }
            resp.addCookie(cookie);
            resp.sendRedirect("cart.jsp");
        }else{
            //将未登录时选购的商品加入登录后的用户中
            System.out.println("成功");
            List<Cart> carts = cartDao.getCarts();
            for(Cart c : carts){
                cartDao.cartGoodAdd(c.getGid(),user.getId(),c.getCount());
            }
            //清空未登录时的购物车
            cartDao.clear();
            //通过userid查询购物车数据

            List<CartDetails> cartDetails = cartServiceImpl.findGoodsByUserId(user.getId());
            session.setAttribute("cartDetails",cartDetails);
            resp.sendRedirect("cart.jsp");
        }

    }
}
